//
//  ACEPublicTool.m
//  ACE
//
//  Created by zhangtao on 2018/8/13.
//  Copyright © 2018年 zt.td. All rights reserved.
//

#import "ACEPublicTool.h"
#import "AppDelegate.h"
@implementation ACEPublicTool



//alertViewcontroller
+(id)initAlertCtlWithTitle:(NSString *)title andMessage:(NSString *)msg andShowCancel:(BOOL)is_showcancel andShowTure:(BOOL)is_showTure  andViewController:(UIViewController *)ctl{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:msg preferredStyle:UIAlertControllerStyleAlert];
    
    if (is_showcancel) {
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cancel];
    }
    
    if (is_showTure) {
        
        UIAlertAction *def = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:def];
    }
    
    [ctl presentViewController:alert animated:YES completion:nil];
    return nil;
}

//alertViewcontroller
+(id)initAlertCtlWithTitle:(NSString *)title andMessage:(NSString *)msg andShowCancel:(BOOL)is_showcancel andShowTure:(BOOL)is_showTure andViewController:(UIViewController *)ctl showTure:(void(^)())showture showCancel:(void(^)())showcancel{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:msg preferredStyle:UIAlertControllerStyleAlert];
    
    if (is_showcancel) {
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            showcancel();
            
            
        }];
        [alert addAction:cancel];
    }
    
    if (is_showTure) {
        
        UIAlertAction *def = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            showture();
            
        }];
        [alert addAction:def];
    }
    
    
    [ctl presentViewController:alert animated:YES completion:nil];
    return nil;
}



-(void)alertViewTrue{
    
}

+(void)writeDataToPlist:(id)data andPlistName:(NSString *)plistName{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *plist = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]];
    NSLog(@"plist存储路径：%@",plist);
    [data writeToFile:plist atomically:YES];
    
}

+(id)readDataFromPlist:(NSString *)plistName andWillBackType:(NSString *)type{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *plist = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]];
    if ([type isEqualToString:@"NSArray"]) {
        NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:plist];
        return array;
    }
    if ([type isEqualToString:@"NSDictionary"]) {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:plist];
        return dic;
    }
    return nil;
    
}

#pragma mark - 根据图片url获取图片尺寸
+(CGSize)getImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;                  // url不正确返回CGSizeZero
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))                    // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}
//  获取PNG图片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
    }];
    
    
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取gif图片的大小
+(CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取jpg图片的大小
+(CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}



//获取文本内容高度
+(CGSize)textViewTextFont:(UIFont *)font andText:(NSString *)textStr Weight:(CGFloat)weight andHeight:(CGFloat)height{
    NSStringDrawingOptions option = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    CGRect rect = [textStr boundingRectWithSize:CGSizeMake(weight, height) options:option attributes:attributes context:nil];
    
    return rect.size;
}

+(CGSize)textViewWeightWithTextFont:(UIFont *)font andText:(NSString *)testStr andSize:(CGSize)size{
    CGSize titleSize = [testStr boundingRectWithSize:
                        size
                                             options:NSStringDrawingTruncatesLastVisibleLine |
                        NSStringDrawingUsesLineFragmentOrigin  |
                        NSStringDrawingUsesFontLeading
                                          attributes:@{NSFontAttributeName:font}
                                             context:nil].size;
    
    return titleSize;
}

+(NSString *)md5:(NSString *)str{
    const char *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (int)strlen(cStr),digest);
    
    //    NSMutableString *output = [NSMutableString stringWithCapacity:COLORSYNC_MD5_LENGTH *2];
    //
    //    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
    //        [output appendFormat:@"%02x",digest[i]];
    //    }
    //    return output;
    
    return [NSString stringWithFormat:
            @"%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
            digest[0], digest[1], digest[2], digest[3],
            digest[4], digest[5], digest[6], digest[7],
            digest[8], digest[9], digest[10], digest[11],
            digest[12], digest[13], digest[14], digest[15]
            ];
}

+(NSAttributedString *)initAttributedString:(NSString *)str andTextColor:(UIColor *)color andTextSize:(NSInteger)size{
    
    NSAttributedString *attrStr = [[NSAttributedString alloc]initWithString:str attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:size],
                                                                                             NSForegroundColorAttributeName:color,
                                                                                             NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle),
                                                                                             NSStrikethroughColorAttributeName:[UIColor blackColor],
                                                                                             NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)                                                   }];
    //     NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle) 10.3之后需要添加上，不添加，删除线等对中文无效
    return attrStr;
}


+(NSString *)timeIntervalChangeToNowTime:(NSString *)intervalTime{
    
    //时间戳转换－－－》》》
    NSString *timeDate = intervalTime;
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeDate doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    
    return dateString;
}

+(NSString *)dateFormatterChangeToInvertalTimeForMilisecondWithString:(NSString *)str andFormatterStyle:(NSString *)style{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:style];
    NSDate *date = [formatter dateFromString:str];
    NSTimeInterval interval = [date timeIntervalSince1970];
    
    NSString *stringInterval = @"";;
    //    if ([style isEqualToString:FORMATTER]) {
    stringInterval = [NSString stringWithFormat:@"%.0f",interval*1000];
    //    }
    
    return stringInterval;
    
}

+(NSString *)intervalChangeToTimeWithFormtterStyle:(NSString *)style andInvertal:(id)interval{
    NSString *intervalStr = [NSString stringWithFormat:@"%@",interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:style];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[intervalStr doubleValue]/1000.0];
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}

+(NSString *)getCurrentTimeWithFormatterType:(NSString *)type{
    NSDate*nowDate = [NSDate date];
    NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:type];
    NSString *the_date_str = [date_formatter stringFromDate:nowDate];
    
    return the_date_str;
}

-(void)test{
    
}


+ (BOOL)validatePhoneNumber:(NSString *)num{
    
    NSString *MOBILE = @"^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:num];
}


+(NSMutableDictionary *)VEComponentsStringToDic:(NSString*)result{
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    
    NSArray *FirstArr=[result componentsSeparatedByString:@"\"&"];
    
    for (int i=0; i<FirstArr.count; i++) {
        NSString *Firststr=FirstArr[i];
        NSArray *SecondArr=[Firststr componentsSeparatedByString:@"=\""];
        [dic setObject:SecondArr[1] forKey:SecondArr[0]];
        
    }
    
    return dic;
}

+(BOOL)isLoginWithController:(UIViewController *)controller{
//    BOOL isLogin = USERDEF_GET_OBJ(LOGIN_STATUS);
//    if (!isLogin) {
//        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//        BFLoginController *login = [storyboard instantiateViewControllerWithIdentifier:@"LOGIN"];
//        [controller presentViewController:login animated:YES completion:nil];
//    }
//    return isLogin;
    return NO;
}


+(NSData *)reSizeImage:(UIImage *)sourceImage maxSizeWithKB:(CGFloat)maxSize{
    if (maxSize <= 0.0) maxSize = 1024.0;
    
    NSData *imageData = UIImageJPEGRepresentation(sourceImage,1.0);
    CGFloat sizeOriginKB = imageData.length / 1024.0;
    
    CGFloat resizeRate = 0.9;
    while (sizeOriginKB > maxSize && resizeRate > 0.1) {
        imageData = UIImageJPEGRepresentation(sourceImage,resizeRate);
        sizeOriginKB = imageData.length / 1024.0;
        resizeRate -= 0.1;
    }
    
    return imageData;
    
    
}

+(NSString *)phoneNumWithString:(NSString *)string{
    for (NSInteger i = [string length]-1; i>-1; i--) {
        NSString *s = [string substringWithRange:NSMakeRange(i, 1)];
        NSLog(@"string is %@",s);
        if (![@"0123456789" containsString:s]) {
            NSRange range = NSMakeRange(i, 1);
            string =   [string stringByReplacingCharactersInRange:range withString:@""];
        }
    }
    return string;
    
}

+(void)showToastInWindow:(id)obj{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window makeToast:obj duration:1 position:CSToastPositionCenter];
}

+(void)showToastActivity{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window makeToastActivity:CSToastPositionCenter];
}

+(void)hidenToastActivity{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window hideToastActivity];
}

+(NSString*)stringFromDate:(NSDate *)date{
    NSDateFormatter *sdf = [[NSDateFormatter alloc] init];
    [sdf setDateFormat:@"yyyy年MM月dd日HH时mm分"];
    return [sdf stringFromDate:date];
}

@end
